#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "../comm/util.hpp"
#include "../comm/log.hpp"


namespace ns_compile
{
    using namespace ns_compile;
    using namespace ns_log;

    class compile
    {
    public:
        compile(){}
        ~compile(){}
    public:
        static bool Compile(const std::string& file_name)
        {
            pid_t pid = fork();
            if(pid < 0)
            {
                LOG(ERROR) << "创建子进程失败" << std::endl;
                return false;
            }
            else if(pid == 0)
            {
                std::string file_path = PathUtil::CompileErrorFile(file_name);
                umask(0);
                int _stderr = open(file_path.c_str(), O_CREAT | O_WRONLY, 0664);
                if(stderr < 0)
                {   
                    LOG(WARNING) << "生成错误文件失败" << std::endl;
                    exit(1);
                }
                dup2(_stderr, 2);
                
                execlp("g++", "g++", "-o", PathUtil::ExeFile(file_name).c_str(), \
                PathUtil::SrcFile(file_name).c_str(), "-std=c++11", "-D", "COMPILER_ONLINE", nullptr);
                LOG(ERROR) << "调用g++编译器编译失败" << std::endl;
                exit(2);
            }
            else
            {
                waitpid(pid, nullptr, 0);
                bool ret = FileUtil::isFileExist(PathUtil::ExeFile(file_name));
                if(ret)
                {
                    LOG(INFO) << "成功生成可执行文件" << std::endl;
                    return true;
                }
            }
            LOG(ERROR) << "提供编译服务失败" << std::endl;
            return false;
        }
    };
}